package com.yiboshi.rehrs.helper;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.BiMap;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.HashBiMap;
import com.yiboshi.rehrs.config.RehrsSystemConfig;
import com.yiboshi.rehrs.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class LimitHelper {



    //内存中 未登录授权
    public final static Set<String> ALL_NAUTH_SET  = new HashSet<>();
    static {
        putNAuth();
        //ALL_NAUTH_SET.hashCode();

    }


    //public final static BiMap<String, String> ALL_SAUTH_BIMAP = new BiMap<>(new HashMap<>());


    public final static Map<String,String> ALL_SAUTH_HASH_MAP = new ConcurrentHashMap<>();

    public static boolean checkNAuth(String nauth) {
        if(StrUtils.isBlank(nauth)||nauth.length()!=40){
            return false;
        }
        return ALL_NAUTH_SET.contains(nauth);

    }


//40位
    public static Set<String> putNAuth() {
        //2017000724011
        int i = 0;
        String day = LocalDate.now().toString();
        String gud = "AB98JdMd#";

        String suffixSalt = "af@10T$H";
        //0077,  2025-06-29 AB98JdMd#
        int count = 0;
        while (i < 100) {
            String paddedNumber = String.format("%04d", i);
            String code =paddedNumber + day + gud;
            String key1 = MD5.encode(code);

            //nauth
            String key2 =key1 + MD5.encode(key1+suffixSalt).substring(7, 15);
            ALL_NAUTH_SET.add( key2);
            //log.info("key1:{},nauth:{}",key1,key2);
            i++;
            count++;
        }
        if(count!=100){
            throw  new RuntimeException("nauth 初始化失败");
        }
         return ALL_NAUTH_SET;
    }


    JedisPool localjedisPool =null;

    static String suffixSalt = "sU78+@Mk";

    //日期+账号+模式 + md5
    public static String getVipSauth(String  account,int mode) {
        String context = qianzui(account,mode);//(日期+账号+模式 + md5) 截取32位

        context = context + MD5.encode(context+suffixSalt).substring(7, 15);
        //ALL_SAUTH_HASH_MAP.putIfAbsent(context,"1");
        return mode==0?context: context.toUpperCase();
    }
    public static String qianzui(String account,int mode) {
        String context = DateUtils.toInt(LocalDate.now())+account;
        context =  context+MD5.encode(context+mode);
        context = context.substring(0, 32);
        return context;

    }
    public static String getSAuth(String  account,int mode) {
        return getVipSauth(account,mode);
    }
    //40位
    /*public String getSAuth(String  account,int mode) {
        //return "0kdklsdfhksf348fjfdgjoert";
        int second = 3600 * 24*3;

        try (Jedis jedis = localjedisPool.getResource()) {
            jedis.select(mode);
            //3天有效
            String key_account = "account:sauth-"+account;
            String oldValue = jedis.get(key_account);
            if(StrUtils.isNotBlank(oldValue)){
                ThreadPoolUtils.submitTask(()->{
                   String lockKey = "expire:"+key_account;
                    String byCache10Hour = CacheUtils.getByCache10Hour(lockKey, String.class);
                    if(StrUtils.isNotBlank(byCache10Hour)){
                        return;
                    }
                    jedis.expire(key_account, second);
                    jedis.expire("sauth:"+oldValue, second);
                    ALL_SAUTH_HASH_MAP.putIfAbsent(oldValue,account);
                    CacheUtils.putByCache10Hour(lockKey,"1");
                });
                return oldValue;
            }
            //nginx auth 规则授权
            String context = qianzui(account);
            context = context + MD5.encode(context+suffixSalt).substring(7, 15);
            jedis.setex(key_account, second, context);
            jedis.setex("sauth:"+context,second,account);
            ALL_SAUTH_HASH_MAP.putIfAbsent(context,account);
            return context;
            //一个account只能有一个sauth
        }catch (Exception e){
            log.error("getSAuth error,{}",e.getMessage());
            return "";
        }
        //String nn = "h4kdg294g076lkjds4*g";
        //ALL_SAUTH_HASH_MAP.putIfAbsent(nn,account);
        //return nn;

        //
    }*/



    //type=1非登录用户 其他是登录用户
    // Java示例代码
    public void updateNginxAuth(String auth, Integer type) {
        String url = "http://47.117.140.195/internal/update_auth";
        Map<String, String> params = new HashMap<>();
        params.put("authCode", auth);
        params.put("type", type.toString()); // true/false
        HttpResponse httpResponse = HttpClientUtils.doGet(url, "", null, params);
        if (httpResponse != null) {
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                log.info("auth:{},type:{} 成功",auth, type);
            } else {
                log.info("auth:{},type:{} 失败",auth, type);
                DingdingUtils.sendMessageByLocal("更新授权异常",auth+"-"+type);
                // 登录失败
            }
        }

        // 发送HTTP请求到Nginx内部接口
        //HttpClient.post(url, params); // 需实现HTTP客户端
    }

    @Value("${localJedis.host}")
    private String localJedisHost;
    @Value("${localJedis.port}")
    private int localJedisPort;
    @Value("${localJedis.password}")
    private String localJedisPassword;
    @Value("${localJedis.timeout}")
    private int localJedisTimeout;

    @PostConstruct
    public JedisPool initLocalJedisPool() {
        // 创建连接池配置
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(8);         // 最大连接数
        poolConfig.setMaxIdle(4);           // 最大空闲连接
        poolConfig.setMinIdle(2);
        poolConfig.setTestOnBorrow(true);   // 获取连接时测试可用性
        poolConfig.setTestWhileIdle(true);  // 空闲时定期测试
        // 创建连接池
        localjedisPool = new JedisPool(poolConfig, localJedisHost, localJedisPort, localJedisTimeout, localJedisPassword);
        return localjedisPool;
    }



}
